package com.wgj.android.fragment;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.jiaai.xui.XUI;
import com.jiaai.xui.adapter.XRecyclerViewAdapter;
import com.jiaai.xui.adapter.XViewHolder;

import com.jiaai.xui.adapter.decoration.DividerDecoration;
import com.jiaai.xui.icon.utils.IconUtils;
import com.jiaai.xui.utils.XDensityUtils;
import com.jiaai.xui.utils.XThemeUtils;
import com.jiaai.xui.utils.http.HttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.jiaai.xui.utils.imageload.XImage;
import com.jiaai.xui.view.widget.XAlertMsgDialog;
import com.jiaai.xui.view.widget.XLoadingDialog;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.R;
import com.wgj.android.accesslibility.config.WXConfginUtil;
import com.wgj.android.accesslibility.service.WGJAccessServier;
import com.wgj.android.accesslibility.service.WXShareAccesslibilityService;
import com.wgj.android.base.BannerHolderView;
import com.wgj.android.base.entity.Action;
import com.wgj.android.base.entity.Banner;
import com.wgj.android.dialog.BAFriendsFormGroupDialog;
import com.wgj.android.dialog.BAFriendsFormLocationDialog;
import com.wgj.android.dialog.WindowPermissionTipsDialog;
import com.wgj.android.entity.Member;
import com.wgj.android.entity.Message;
import com.wgj.android.events.LocationEvent;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.permission.WindowManagerPermission;

import com.wgj.android.ui.activity.BachAddFriendsActivity;
import com.wgj.android.ui.activity.ColumnLiveActivity;
import com.wgj.android.ui.activity.CreateCardActivity;
import com.wgj.android.ui.activity.MessageActivity;
import com.wgj.android.ui.activity.MyPropertyActivity;
import com.wgj.android.ui.activity.MyQrCodeActivity;
import com.wgj.android.ui.activity.MyShareActivity;
import com.wgj.android.ui.activity.ShareCardActivity;
import com.wgj.android.ui.activity.ShareHaoBaoActivity;
import com.wgj.android.ui.activity.ShopStoreActivity;
import com.wgj.android.ui.activity.VideoTuiGuangActivity;
import com.wgj.android.ui.activity.VideoUploadActivity;
import com.wgj.android.ui.activity.WXGroupActivity;
import com.wgj.android.ui.activity.WXHongBaoActivity;
import com.wgj.android.ui.activity.ShareActivity;
import com.wgj.android.utils.AccessibilityUtil;
import com.wgj.android.utils.CacheUtils;
import com.wgj.android.utils.DateUtils;
import com.wgj.android.utils.TextViweUtils;
import com.wgj.android.utils.WXAccessUtil;
import com.wgj.android.utils.fonat.IconFonat;
import com.wgj.android.web.WGJWebActivity;
import com.wgj.android.web.entity.WebConfig;
import com.wgj.android.widget.ScrollBanner;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/11/3.
 */
public class HomeFragment extends Fragment implements XRecyclerViewAdapter.OnItemClickListener ,View.OnClickListener{

    private List<Message> list = new ArrayList<Message>();
    private  int size=0;
    private  int num;
    @BindView(R.id.bannerView)
    ConvenientBanner bannerView;

    @BindView(R.id.location)
    TextView locationView;

    @BindView(R.id.megView)
    ImageView msgView;

    @BindView(R.id.contentView)
    RecyclerView contentView;


    @BindView(R.id.adv1)
    ImageView advImagView1;

    @BindView(R.id.adv2)
    ImageView adv2;

    @BindView(R.id.scrollBanner)
    ScrollBanner scrollBanner;

    @BindView(R.id.number)
    TextView number;

    private List<String> advs=new ArrayList<>();
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
         View view=inflater.inflate(R.layout.home_fragment,container,false);
         ButterKnife.bind(this,view);
        EventBus.getDefault().register(this);
         msgView.setBackgroundDrawable(IconUtils.getDrawble(getContext(),IconFonat.Icon.msg_on, XThemeUtils.getColorPrimary(getContext()),26));
         TextViweUtils.setDrawableLeft(locationView,IconFonat.Icon.icon_dizhi,XThemeUtils.getColorPrimary(getContext()),8);
         return  view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void  initView(){

            final List<Banner> banners=new ArrayList<>();
            XHttp.obtain().get(WGJAPI.SELECT_BANNER_URL,null , new HttpCallBack<String>() {

                @Override
                public void onSuccess(String string) {
                    try {

                        JSONObject json = new JSONObject(string);
                        JSONArray jsonArray1 = new JSONArray(json.getString("banner"));
                        //JSONArray jsonArray1 = json.getJSONArray("banner");
                        for(int j= 0;j<jsonArray1.length();j++){
                            JSONObject json2 = jsonArray1.getJSONObject(j);
                            Banner banner = new Banner(json2.getString("imgUrl"));
                            banners.add(banner);
                        }
                        JSONArray jsonArray = new JSONArray(json.getString("news"));
                        for(int i=0;i<jsonArray.length();i++){
                            JSONObject json1 = jsonArray.getJSONObject(i);
                            advs.add(json1.getString("titile"));

                        }
                        scrollBanner.setList(advs);
                        scrollBanner.startScroll();
                        bannerView.setPages(new CBViewHolderCreator<BannerHolderView>() {
                            @Override
                            public BannerHolderView createHolder() {
                                return new BannerHolderView();
                            }
                        },banners)
                                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                                .startTurning(2000)
                                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused});
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailed(int i, String s, boolean b) {
                    XToast.warning("网络异常");
                }
            });
            XImage.getInstance().load(advImagView1,"https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3031374368,1621506714&fm=27&gp=0.jpg");
            XImage.getInstance().load(adv2,"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3307294189,382340473&fm=27&gp=0.jpg");
            List<Action> page1=new ArrayList<>();
              page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_wuxinyongqia, Color.parseColor("#99CCFF"),45),"智能名片"));
                page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_pinpai, Color.parseColor("#CC6666"),45),"品牌商城"));
                page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_live, Color.parseColor("#0099CC"),45),"影视直播"));
              page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_hongbao, Color.parseColor("#FF3366"),45),"共享红包"));
                page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_hongbao, Color.parseColor("#990066"),45),"我的资产"));
              page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_fenxiang, Color.parseColor("#66CCCC"),45),"我的分享"));

              //page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_group, Color.parseColor("#009966"),45),"群加好友"));
              //page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_haoyoutuijian, Color.parseColor("#CC3366"),45),"附近加好友"));
           // page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_jiance, Color.parseColor("#3366CC"),45),"检测清粉"));
//            page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_qingli, Color.parseColor("#3366CC"),45),"高级分享"));
//            page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_hongbao, Color.parseColor("#990066"),45),"红包助手"));
//            page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_group, Color.parseColor("#009966"),45),"群加好友"));
//            page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_haoyoutuijian, Color.parseColor("#CC3366"),45),"附近加好友"));
//            page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_fenxiang, Color.parseColor("#66CCCC"),45),"我的分享"));
//            page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_shangcheng, Color.parseColor("#66CCCC"),45),"品牌联盟"));
//            page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_yuechi, Color.parseColor("#CC3366"),45),"钥匙"));
//            page1.add(new Action(IconUtils.getDrawble(getContext(), IconFonat.Icon.icon_wuxinyongqia, Color.parseColor("#FF9933"),45),"信用卡管家"));
            size=XDensityUtils.getScreenWidth()/3;
            contentView.setLayoutManager(new GridLayoutManager(getContext(),3));
            contentView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
            contentView.addItemDecoration(new DividerDecoration(Color.TRANSPARENT, XDensityUtils.dp2px(20)));
            contentView.setHasFixedSize(true);
            ActionAdapter actionAdapter=new ActionAdapter(contentView,page1,R.layout.action_item_view);
            actionAdapter.setOnItemClickListener(this);
            contentView.setAdapter(actionAdapter);
            msgView.setOnClickListener(this);

            //查询所有未读消息
        XHttp.obtain().get(WGJAPI.UNREAD_MESSAGE_URL + "?mId=" + CacheUtils.getMember().getM_id(), null, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                if(!s.equals("0")){
                    number.setVisibility(View.VISIBLE);

                    number.setText(Integer.parseInt(s)+num+"");
                    num=Integer.parseInt(s)+num;
                }

            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                number.setText("");
            }
        });

    }

    @Override
    public void onClick(View view) {
        number.setVisibility(View.GONE);
       Intent intent = new Intent(getContext(),MessageActivity.class);
       //intent.putExtra("message", (ArrayList<Message>) list);
       startActivity(intent);
    }


    public  class  ContentHolderView  implements Holder<Map<String,List<Action>>>{
        RecyclerView recyclerView;
        @Override
        public View createView(Context context) {
            recyclerView=new RecyclerView(context);
            recyclerView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            recyclerView.setLayoutManager(new GridLayoutManager(context,4));
            recyclerView.setHasFixedSize(true);
            return recyclerView;
        }

        @Override
        public void UpdateUI(Context context, int position, Map<String,List<Action>> data) {
            ActionAdapter actionAdapter=null;
            if(data.containsKey("page1")){
                actionAdapter=new ActionAdapter(recyclerView,data.get("page1"),R.layout.action_item_view);
            }
             recyclerView.setAdapter(actionAdapter);
        }
    }



    public  class ActionAdapter extends XRecyclerViewAdapter<Action> {

        public ActionAdapter(@NonNull RecyclerView mRecyclerView, List<Action> dataLists, int layoutId) {
            super(mRecyclerView, dataLists, layoutId);
        }

        @Override
        protected void bindData(XViewHolder holder, Action action, int i) {
            //holder.getConvertView().setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,size));
            holder.setImageDrawable(R.id.actionIcon,action.getActionIcon());
            holder.setText(R.id.title,action.getTitle());
            if("钥匙".equals(action.getTitle())){
                    TextViweUtils.setDrawableLeft((TextView) holder.getView(R.id.title),IconFonat.Icon.icon_i,Color.RED ,4);
            }

        }
    }
    @Override
    public void onItemClick(View view, int i) {
        Member member= CacheUtils.getMember();
        Intent intent=null;
        WebConfig config=null;
        Bundle bundle=new Bundle();
        switch (i){
            case 0:
                startActivity(new Intent(getContext(),ShareCardActivity.class));

                break;
            case 1:
                WGJWebActivity.openHtml5(this.getContext(),WGJAPI.WEB_URL+"/store/index.html#/index?userId="+CacheUtils.getMember().getM_id(),false);
                break;
            case 2:
                WGJWebActivity.openHtml5(this.getContext(),WGJAPI.WEB_URL+"/live/index.html",false);
                break;
            case 3:
                intent=new Intent(getContext(), ShareHaoBaoActivity.class);
                startActivity(intent);
                break;
            case 4://我的资产
                startActivity(new Intent(getContext(), MyPropertyActivity.class));
                break;
            case 5:
                intent=new Intent(getActivity().getApplication(),ShareActivity.class);
                startActivity(intent);
                break;
            case 6:
                if (!WXAccessUtil.checkAccessRunAmbient(getContext())) {
                    return;
                }
                WXAccessUtil.checkWindowManagerPermission(getContext(), getFragmentManager(), new WindowPermissionTipsDialog.OnNextCallback() {
                    @Override
                    public void onNext() {
                        new BAFriendsFormGroupDialog().show(getFragmentManager(),"BAFriendsFormGroupDialog");
                    }
                });
                break;
            case 7:
                if (!WXAccessUtil.checkAccessRunAmbient(getContext())) {
                    return;
                }
                WXAccessUtil.checkWindowManagerPermission(getContext(), getFragmentManager(), new WindowPermissionTipsDialog.OnNextCallback() {
                    @Override
                    public void onNext() {
                        new BAFriendsFormLocationDialog().show(getFragmentManager(),"BAFriendsFormLocationDialog");
                    }
                });
             break;
            case 8:
                break;
            case 9:
                break;
            default:
                XToast.warning("功能正在研发中,(>^ω^<)喵");
                break;

        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN,sticky =true)
    public void messageEvents(Message message){
        /*i++;
        list.add(message);*/

            advs.add(message.getContent());
            scrollBanner.setList(advs);
            scrollBanner.startScroll();

            num++;
            number.setVisibility(View.VISIBLE);
            number.setText(num+"");



    }
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void locationEvents(LocationEvent event){
        locationView.setText(event.getName());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        bannerView.notifyDataSetChanged();
    }
    //跑马灯消息
    public void message(){

    }
}
